#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

void Usage(std::string proc)
{
    cout << "Usage:\n\t" << proc << " serverip serverport\n" << endl;
}

int main(int argc, char *argv[])
{
    // 接收网络地址
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    // 创建TCP套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        cerr << "socket error" << endl;
        exit(1);
    }
    // 填充网络地址
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    // 向指定的网络地址（服务器地址）发起连接
    int n = connect(sockfd, (struct sockaddr*)&server, sizeof(server));
    if (n < 0)
    {
        cerr << "connect error" << endl;
        exit(1);
    }
    // 向服务器进行通信
    while(true)
    {
        cout << "Please Enter# ";
        string outstring;
        getline(cin, outstring);

        ssize_t s = send(sockfd, outstring.c_str(), outstring.size(), 0); 
        if(s > 0)
        {
            char inbuffer[1024];
            ssize_t m = recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if(m > 0)
            {
                inbuffer[m] = 0;
                cout << inbuffer << endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
    close(sockfd);
    return 0;
}